package bankapplication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Random;
import java.util.zip.DataFormatException;

import bankapplication.com.acme.bankapp.domain.bank.Account;
import bankapplication.com.acme.bankapp.domain.bank.Bank;
import bankapplication.com.acme.bankapp.domain.bank.Client;
import bankapplication.com.acme.bankapp.service.bank.BankDataLoaderService;
import bankapplication.com.acme.bankapp.service.bank.BankService;
import bankapplication.com.acme.bankapp.service.bank.EmailService;
import bankapplication.com.acme.networking.*;

public class BankApplication {
  public static void main(String[] args) {
    String feedfilename = null;
    String loadbankfilename = null;
    boolean servermode = false;
    boolean statisticsmode = false;
    for(int i=0; i<args.length; i++){
      if(args[i].equals("-statistics")){
        statisticsmode = true;
      }
      else if(args[i].equals("-loadfeed")){
        if(i+1 == args.length){
          System.err.println("Опция -loadfeed должна содержать 1 аргумент (подано 0).");
          return;
        }
        feedfilename = args[i+1];
        break;
      }
      else if(args[i].equals("-loadbank")){
        if(i+1 == args.length){
          System.err.println("Опция -loadbank должна содержать 1 аргумент (подано 0).");
          return;
        }
        loadbankfilename = args[i+1];
      }
      else if(args[i].equals("-server")){
        servermode = true;
      }
    }
    if(feedfilename != null && loadbankfilename != null){
      System.err.println("Невозможно одновременно исполнить -loadfeed и -loadbank.");
      return;
    }
    Bank bank = null;
    EmailService emailService = new EmailService();
    if(feedfilename != null){
      try{
        bank = BankDataLoaderService.loadBankFromFile(feedfilename, emailService);
      }
      catch(DataFormatException e){
        System.out.println("Cannot create an instance of Bank; Input file is corrupted");
        System.out.println(e.getMessage());
        emailService.close();
        System.out.println("emailService is successfully closed..");
        return;
      }
    }
    else if(loadbankfilename != null){
      try{
        bank = BankDataLoaderService.readBank();
      }
      catch(DataFormatException e){
        System.out.println("Cannot create an instance of Bank; Input file is corrupted");
        System.out.println(e.getMessage());
        emailService.close();
        System.out.println("emailService is successfully closed..");
        return;
      }
    }
    if(bank == null){
      System.err.println("Банк не загружен в систему!");
      emailService.close();
      System.out.println("emailService is successfully closed..");
      return;
    }
    try{
      BankService.printMaximumAmountToWithDraw(bank);
    }
    catch(DataFormatException e){
      System.err.println(e.getMessage());
    }
    if(servermode){
      startServer(bank);
    }
    if(statisticsmode){
      String command = "";
      System.out.println("Включен режим получения статистики.");
      BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
      do{
        System.out.println("Введите команду...");
        try{
          command = input.readLine();
          if(command.equals("getNbOfCustomers")){
            System.out.println(bankapplication.com.acme.bankapp.domain.bank.BankReport.getNbOfCustomers(bank));
          }
          else if(command.equals("getNbOfAccounts")){
            System.out.println(bankapplication.com.acme.bankapp.domain.bank.BankReport.getNbOfAccounts(bank));
          }
          else if(command.equals("getAccountsSortedBySum")){
            System.out.println(bankapplication.com.acme.bankapp.domain.bank.BankReport.getAccountsSortedBySum(bank));
          }
          else if(command.equals("getBankCredit")){
            System.out.println(bankapplication.com.acme.bankapp.domain.bank.BankReport.getBankCredit(bank));
          }
          else if(command.equals("getCustomerAccount")){
            System.out.println(bankapplication.com.acme.bankapp.domain.bank.BankReport.getCustomerAccount(bank));
          }
          else if(!command.equals("quit")){
            System.out.println("Команда не найдена.");
          }
        }
        catch(IOException e){
          System.err.println("Cannot read from System.in..");
          e.printStackTrace();
        }
      }while(!command.equals("quit"));
    }
    emailService.close();
    System.out.println("emailService is successfully closed..");
  }
  static void modifyBank(Bank bank){
    Random rand = new Random();
    Iterator<Client> clientiter = bank.getClients().iterator();
    while(clientiter.hasNext()){
      Iterator<Account> accountiter = clientiter.next().getAcconts().iterator();
      while(accountiter.hasNext()){
        accountiter.next().deposit(rand.nextInt(100));
      }
    }
  }
  static void printBalance(Bank bank){
    Iterator<Client> clientiter = bank.getClients().iterator();
    while(clientiter.hasNext()){
      Iterator<Account> accountiter = clientiter.next().getAcconts().iterator();
      while(accountiter.hasNext()){
        System.out.println(accountiter.next().getBalance());
      }
    }
  }
  static void printClientSalutations(Bank bank){
    Iterator<Client> clientiter = bank.getClients().iterator();
    while(clientiter.hasNext()){
      clientiter.next().getClientSaltation();
    }
  }
  static void startServer(Bank bank) {
    BankServer bankserver = new BankServer();
    bankserver.startServer(bank);
  }
}
